package utils

/*
 * global context object.
 */

import (
	"context"
	"sync"
)

// Context cancel interface.
type IContextCancel interface {
	WGAdd()
	WGDone()
	WGWait()

	Cancel()
	CancelDone()
	ExitAndWait()
}

type ContextInfo struct {
	Context context.Context
	Cancel  context.CancelFunc
	wg      sync.WaitGroup
}

// workgroup's function.
func (ci *ContextInfo) Add() {
	ci.wg.Add(1)
}
func (ci *ContextInfo) Done() {
	ci.wg.Done()
}
func (ci *ContextInfo) Wait() {
	ci.wg.Wait()
}

// exit and wait.
func (ci *ContextInfo) ExitAndWait() {
	ci.Cancel()
	ci.Wait()
}

var ContextInfoObj *ContextInfo

func init() {
	ContextInfoObj = &ContextInfo{}
	ContextInfoObj.Context, ContextInfoObj.Cancel = context.WithCancel(context.Background())
}
